const app = getApp()
import user from '../../utils/user.js'
import {
    getMakeProject,
    joinMakeProject,
    joinPayAddress,
    joinPayProject,
    getPayProject,
    getCompanyName,
    getQrcodeCache,
    getLongInsureInfo,
    joinLongInsure,
    clockInPageData
} from '../../api/app.js'
import {
    joinContractProject
} from '../../api/contract'
import {
    saveInsuranceSalary
} from '../../api/insurance'
import {
    queryVerifyResult,
    setIsOpenSalary
} from '../../api/salary-card.js'
import {
    openSalaryCard,
    querySalaryCard,
    verifyFace
} from '../../utils/salary-card.js'
import {
    dateFormat,
    anit,
    goToContract,
    getCardAge,
    toast
} from '../../utils/util.js'

Page({

    /**
     * 页面的初始数据
     */
    data: {
        clock: false,
        longitude: '',
        latitude: '',
        markers: [],
        projectName: '',
        companyName: '',
        companyId: '',
        serveCompanyName: '',
        projectId: '',
        btnText: '加入项目',
        isContract: false,
        salaryCardCallBack: () => {},
        projectInfo: {},
        titleText: '',
        longInsureId: '',
        isExit: false, // 拒签后的显示
    },
    toservice(){
        wx.navigateTo({
            url: '/pages/service/service',
        })
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        console.log(options, 'options')
        this.setData({
            options
        })
    },
    onShow() {
        console.log('调用啦没')
        console.log(decodeURIComponent(this.data.options.scene).split('&')[0].split('=')[1], 'this.data.options.scene')
        if (this.data.authenticateNumber && app.options.scene == 1038) {
            queryVerifyResult({
                authenticateNumber: this.data.authenticateNumber,
                companyId: this.data.companyId
            }).then(res => {
                console.log('核实信息', res)
                if (res.authenticateState === 'AUTHENTICATE_SUCCESS') {
                    console.log('核身信息入参', {
                        authenticateNumber: res.authenticateNumber,
                        openid: user.openid,
                        projectId: this.data.projectId || decodeURIComponent(this.data.options.scene).split('&')[0].split('=')[1],
                        projectLeaderLocation: this.data.coord,
                        workerLocation: this.data.longitude + ',' + this.data.latitude
                    })
                    // 存储核身信息
                    saveInsuranceSalary({
                        authenticateNumber: res.authenticateNumber,
                        openid: user.openid,
                        projectId: this.data.projectId || decodeURIComponent(this.data.options.scene).split('&')[0].split('=')[1],
                        projectLeaderLocation: this.data.coord,
                        workerLocation: this.data.longitude + ',' + this.data.latitude
                    }).then((res) => {
                        console.log(res, '核实调用成功啦吗')
                        // 回调
                        this.onInitJoin()
                        this.data.salaryCardCallBack()
                    }).catch((rej) => {
                        console.log(rej, '失败了吗')
                    })
                }
            })
            app.options = {}
        } else {
            user.waitLogin().then(res => {
                console.log(res, '调用先后')
                this.onInitJoin()
            }, () => {
                this.onInitJoin()
            })
        }

        if (this.data.isContract) {
            console.log('进入这里啦')
            wx.switchTab({
                url: '/pages/index/index'
            })
        }
    },
    onInitJoin() {
        console.log(app.globalData.homePath)
        if (app.globalData.homePath) {
            const homePath = app.globalData.homePath
            app.globalData.homePath = ''
            this.pathJoin(homePath)
        } else if (this.data.options.scene) {
            this.pathJoin(this.data.options.scene)
            // 之前是不注销的
            // this.setData({
            //     ['options.scene']: ''
            // })
        } else if(this.data.options.q) {
            console.log(11111, this.data.options.q)
            const scene = decodeURIComponent(this.data.options.q).split('&')[1]
            const sceneData = scene.split('=')[1]
            console.log(123, sceneData)
            this.pathJoin(sceneData)
        }
    },
    getUrl(url) {
        console.log(666, url)
        if (url.indexOf('%') === -1) {
            return url
        } else {
            const newUrl = decodeURIComponent(url)
            return this.getUrl(newUrl)
        }
    },
    // 通过路径获取路径中的变量，进行操作
    pathJoin(path) {
        console.log(44444, path)
        let scene = this.getUrl(path)// decodeURIComponent(path)
        console.log(scene, 'pathpath')
        const option = []
        scene = scene.split('&')
        this.data.path = path

        console.log(9999, scene)

        for (const i in scene) {
            const query = scene[i].split('=')
            option[query[0]] = query[1]
        }
        console.log(option, option.LIKey, 'option')
        if (option.type) {
            console.log('进入下一步')
            // 从注册页面回来并且有type  自动执行下一步
            this.onNext()
        }
        if (option.cacheId) {
            getQrcodeCache({
                key: option.cacheId
            }).then(res => {
                console.log(res, 'resresfsgdgh')
                this.pathJoin(encodeURIComponent(res.data))
            })
        } else if (option.projectId) // 加入记名单项目
            this.joinMakeProject(option.projectId)
        else if (option.PCID) // 加入发薪端员工通讯录
            this.joinPayAddress(option.PCID, option.UID) // PCID   pay company id    发薪端公司ID			
        else if (option.INID && option.UID) // 加入投保项目
            // this.joinMicroProject(option.MPID, option.UID, option.ADDT)
            this.joinInsurance(option.INID, option.UID, option.coord, option.authenticateNumber) // INID   insurance id      保险项目ID
        else if (option.PPID) // 加入发薪项目
            this.joinPayProject(option.PPID, option.UID, option.ADDT) // PPID   pay project id    发薪端项目ID
        else if (option.COID) // 加入合同项目
            this.joinContractProject(option.COID, option.UID) // PPID   pay project id    发薪端项目ID
        else if (option.LIKey) {
            console.log(121111)
            this.joinLongInsure(option.LIKey, option.Id, this.onNext)
        } else if (option.MPID) {
            return
        } else if (option.tJ) {
            wx.navigateTo({
			  url: `/pages/job-detail/job-detail?id=${option.id}&uid=${option.uid}&force=${option.force}`,
            })
        } else {
            app.alert('请使用正确的小程序码')
        }
    },

    isNeedLogin(companyId, type = 0, companyName = '', projectName = '', projectId = '') {
        console.log('进入这里啦1')
        return new Promise((resolve) => {
            user.waitLogin().then(() => {
                resolve()
            }, () => {
                app.globalData.companyId = companyId
                app.globalData.companyName = companyName
                app.globalData.projectName = projectName
                app.globalData.projectId = projectId
                app.globalData.homePath = this.data.path + encodeURIComponent('&type=' + type)
                console.log(app.globalData.homePath, 'app.globalData.homePath')
                user.goRegister(true)
            })
        })
    },
    // 加入合同项目
    joinContractProject(projectId, uid) {
        this.isNeedLogin().then(() => {
            joinContractProject({
                createUserId: uid,
                projectId: projectId
            }).then(res => {

                if (res.signUrls)
                    this.setData({
                        isContract: true,
                        projectName: res.templateName,
                        companyName: res.serverCompanyName,
                        btnText: '点击立即签署合同',
                        callBack: () => {
                            goToContract(res.signUrls, res.id)
                        }
                    })
                else {
                    this.setData({
                        isContract: true,
                        projectName: res.templateName,
                        companyName: res.serverCompanyName,
                        btnText: '返回首页',
                        callBack: () => {
                            wx.switchTab({
                                url: '/pages/index/index'
                            })
                        }
                    })
                }
            }).catch((rej) => {
                if (rej.data.msg === '你已加入项目') {
                    this.setData({
                        btnText: '确定',
                        titleText: '你已在该签署项目中请勿重复操作',
                        titleTips: '如已失效,可联系劳务重新发起签署',
                        isExit: true,
                        callBack: () => {
                            wx.switchTab({
                                url: '/pages/index/index'
                            })
                        }
                    })
                } else {
                    this.setData({
                        btnText: '返回',
                        titleText: '加入失败',
                        titleTips: rej.data.msg,
                        callBack: () => {
                            wx.switchTab({
                                url: '/pages/index/index'
                            })
                        }
                    })
                }
				
                console.log(rej, 'rejrejrej')
            })
        })
    },
    // 长期工保险登记
    joinLongInsure(key, id, callback) {
        this.setData({
            LongInsureId: id
        })
        this.isNeedLogin().then(() => {
            getLongInsureInfo({
                companyPlanId: id
            }).then(res => {
                this.setData({
                    titleText: '投保信息登记',
                    btnText: '立即登记',
                    callBack: () => {
                        return new Promise(() => {
                            joinLongInsure({
                                key: key,
                                id
                            }).then(() => {
                                console.log(res, 'res')
                                if (res.companyId) {
                                    this.goRecruitSuccess('登记成功', '', 'success', res.companyId)
                                } else {
                                    this.goSuccess('登记成功', '', 'success')
                                }
                                // this.goSuccess('登记成功', '', 'success')
                                // this.goRecruitSuccess('登记成功', '', 'success', this.data.id)
                            })
                        })
                    }
                })
                console.log(212121, callback)
                callback && callback()
            })
        })
    },
    // 加入记名单项目
    joinMakeProject(projectId) {
        this.isNeedLogin().then(() => {
            getMakeProject({
                id: projectId
            }).then(res => {
                const projectTime = new Date(new Date(res.createTime).toLocaleDateString())
                const cutOffTime = new Date(projectTime.setDate(projectTime.getDate() + 1)).getTime()
                console.log(cutOffTime)
                if (cutOffTime < new Date().getTime()) {
                    this.setData({
                        projectName: res.supplierName,
                        companyName: res.companyName,
                        btnText: '项目已结束',
                        callBack: () => {}
                    })
                    return 0
                }
                this.setData({
                    projectName: res.supplierName,
                    callBack: () => {
                        return new Promise(() => {
                            joinMakeProject({
                                userId: user.userId,
                                projectId: projectId
                            }).then(() => {
                                this.goSuccess('加入项目成功', '你可以在工作记录中查看', 'success')
                            })
                        })
                    }
                })
            })
        })
    },
    // 加入新保险项目 和发薪一个接口 只不过逻辑不一样
    async joinMicroProject(projectId, uid, type) {
        console.log(type, 'typetypetype')
        const result = await getPayProject({
            id: projectId
        })
        console.log('joinPayProject微保项目调用成功', result)
        this.setData({
            projectInfo: result,
            projectId: result.id
        })
        if (result.params.isJoinProject) {
            this.setData({
                projectName: result.projectName,
                companyName: result.companyName,
                serveCompanyName: result.serveCompanyName,
                titleText: '该项目您已加入，无需再次加入',
                btnText: '返回',
                callBack: () => {
                    wx.switchTab({
                        url: '/pages/clock/clock'
                    })
                }
            })
            if (!result.params.isAuthed) {
                console.log('已加入项目但未核实')
                this.queryRelations(result.companyId)
                return
            }
            return
        }
        if (result.wesureState !== 0) {
            this.setData({
                projectName: result.projectName,
                companyName: result.companyName,
                serveCompanyName: result.serveCompanyName,
                btnText: '该项目已过期',
            })
            return
        }
        this.isNeedLogin(result.companyId, result.type).then(() => {
            joinPayProject({
                createUserId: uid,
                userId: user.userId,
                projectId: projectId,
                joinType: 0
            }).then(() => {
                this.setData({
                    projectName: result.projectName,
                    serveCompanyName: result.serveCompanyName,
                    btnText: '返回',
                    callBack: () => {
                        wx.switchTab({
                            url: '/pages/index/index'
                        })
                    }
                    // callBack: app.globalData.gscJoin
                })
                toast('去扫脸')
                this.queryRelations(result.companyId)
                return
            }).catch((rej) => {
                console.log(rej, 'rejrej')
                if (rej.data.code === 500) {
                    this.setData({
                        btnText: '返回',
                        titleText: '加入失败',
                        titleTips: rej.data.msg,
                        callBack: () => {
                            wx.switchTab({
                                url: '/pages/index/index'
                            })
                        }
                    })
                    return
                }
                if (rej.data.data === 'checkAge') {
                    setTimeout(() => {
                        wx.switchTab({
                            url: '/pages/index/index'
                        })
                    }, 1500)
                    return
                }

            })
        })
        console.log(result, 'result')
    },
    // 加入发薪项目
    joinPayProject(projectId, uid, type) {
        console.log(type, 'typetypetype')
        console.log('joinPayProject发薪方法调用成功')
        getPayProject({
            id: projectId
        }).then(async res => {
            console.log(res, 'resresres')
            this.setData({
                projectInfo: res
            })
            console.log(res, 'res')
            if (res.params.isJoinProject) {
                this.setData({
                    projectName: res.projectName,
                    companyName: res.companyName,
                    serveCompanyName: res.serveCompanyName,
                    titleText: '您已加入过此项目',
                    btnText: '返回',
                    callBack: () => {
                        wx.switchTab({
                            url: '/pages/clock/clock'
                        })
                    }
                })
                return
            }
            if (res.wesureState !== 0) {
                this.setData({
                    projectName: res.projectName,
                    companyName: res.companyName,
                    serveCompanyName: res.serveCompanyName,
                    btnText: '该项目已过期',
                })
                return
            }
            let age = getCardAge(user.cardNo)
            let sex = user.sex
            if (sex == '0') {
                if (user.userId && res.ageRange && (age < res.ageRange.split('-')[0] || age > res.ageRange.split('-')[1])) {
                    this.setData({
                        btnText: '返回',
                        titleText: '加入失败',
                        titleTips: '年龄不符合要求，请咨询领队',
                        callBack: () => {
                            wx.switchTab({
                                url: '/pages/index/index'
                            })
                        }
                    })
                    console.log(this.data.callBack, 'this.data.callBack')
                    // await app.alert('当前年龄不符')
                    return
                }
                console.log('进入了吗')
            } else {
                if (user.userId && res.ageRangeFemale && (age < res.ageRangeFemale.split('-')[0] || age > res.ageRangeFemale.split('-')[1])) {
                    this.setData({
                        btnText: '返回',
                        titleText: '加入失败',
                        titleTips: '年龄不符合要求，请咨询领队',
                        callBack: () => {
                            wx.switchTab({
                                url: '/pages/index/index'
                            })
                        }
                    })
                    console.log(this.callBack())
                    // await app.alert('当前年龄不符')
                    return
                }
            }
            console.log('出来了吗')
            user.isNeedAuthSalaryCard = res.params.isNeedAuthSalaryCard
            //
            console.log('joinPayProject111')
            this.isNeedLogin(res.companyId, res.type).then(() => {
                joinPayProject({
                    createUserId: uid,
                    userId: user.userId,
                    projectId: projectId,
                    joinType: 0
                }).then(() => {
                    this.setData({
                        projectName: res.projectName,
                        serveCompanyName: res.serveCompanyName,
                        btnText: '返回',
                        callBack: () => {
                            wx.switchTab({
                                url: '/pages/index/index'
                            })
                        }
                        // callBack: app.globalData.gscJoin
                    })
                    if (!type) {
                        this.goSuccess('加入项目成功!', '加入项目【' + res.projectName + '】成功！', 'success')
                    } else {
                        this.goRecruitSuccess('加入项目成功!', '加入项目【' + res.projectName + '】成功！', 'success')
                    }
                }).catch((rej) => {
                    console.log(rej, 'rejrej')
                    // 
                    if (rej.data.code === 500) {
                        this.setData({
                            btnText: '返回',
                            titleText: '加入失败',
                            titleTips: rej.data.msg,
                            callBack: () => {
                                wx.switchTab({
                                    url: '/pages/index/index'
                                })
                            }
                        })
                        return
                    }
                    if (rej.data.data === 'checkAge') {
                        setTimeout(() => {
                            wx.switchTab({
                                url: '/pages/index/index'
                            })
                        }, 1500)
                        return
                    }

                })
            })
        })
    },
    // 加入发薪端通讯录
    joinPayAddress(companyId, uid) {
        this.isNeedLogin(companyId).then(() => {
            getCompanyName({
                companyId
            }).then(async (res) => {
                this.setData({
                    companyName: res.companyName,
                    btnText: '返回',
                    callBack: () => {
                        wx.switchTab({
                            url: '/pages/index/index'
                        })
                    }
                })
                joinPayAddress({
                    companyId,
                    createUserId: uid
                }).then(() => {
                    this.goSuccess('加入通讯录成功!', '', 'success')
                })
            })
        })
    },
    onNext() {
        console.log('调用卡22')
        // 当项目type是0或1 并且 商户号等于0 并且 该公司已开启强制开通微工卡 则触发
        if (user.isNeedAuthSalaryCard && user.isOpenSalaryCard == 0 && (this.data.projectInfo.type == 0 || this.data.projectInfo.type == 1)) {
            app.confirm('请先开通微工卡,否则无法加入该项目').then(() => {
                console.log(app.globalData.companyId, app.globalData.companyName, app.globalData.projectId, user.userName, user.cardNo)
                openSalaryCard(this.data.projectInfo.companyId, user.userName, user.cardNo).then(res => {
                    console.log(res, 'res微工卡')
                    user.isOpenSalaryCard = res.subMchid
                    setIsOpenSalary({
                        isOpenSalaryCard: res.subMchid
                    })
                })
            })
            return
        }
        console.log(this.data.callBack, '调用卡')
        anit(this.data.callBack)
    },
    goSuccess(title, content, type) {
        wx.reLaunch({
            url: '/pages/success/success?title=' + title + '&content=' + content + '&type=' + type + '&color=#04CD5A',
        })
    },
    goRecruitSuccess(title, content, type) {
        console.log(this.data.LongInsureId, 'LongInsureIdLongInsureId')
        wx.reLaunch({
            url: '/pages/job-status/job-status?title=' + title + '&content=' + content + '&type=' + type + '&color=#04CD5A' + (this.data.projectInfo.companyId ? '&id=' + this.data.projectInfo.companyId : 6),
        })
    },
    // 加入新投保项目
    async joinInsurance(insuranceId, userId, coord, authenticateNumber = '') {
        console.log('加入投保项目加入投保项目', insuranceId, userId, coord, authenticateNumber)
        this.getPosition()
        getPayProject({
            id: insuranceId
        }).then(res => {
            this.setData({
                projectId: res.id
            })
            console.log(res, '岗位信息接口')
            this.isNeedLogin(res.companyId, res.type, res.serveCompanyName, res.projectName, insuranceId).then(() => {
                // if (res.params.isJoinProject) {
                //     this.setData({
                //         projectName: res.projectName,
                //         companyName: res.companyName,
                //         serveCompanyName: res.serveCompanyName,
                //         btnText: '您已加入该项目',
                //     })
                //     return
                // }
                if (!res.isOpenWesure) {
                    console.log('joinPayProject222')
                    this.joinPayProject(insuranceId, userId)
                    return
                }
                if (res.params.isJoinProject) {
                    this.setData({
                        projectName: res.projectName,
                        companyName: res.companyName,
                        serveCompanyName: res.serveCompanyName,
                        titleText: '您已加入过此项目',
                        btnText: '返回',
                        callBack: () => {
                            wx.switchTab({
                                url: '/pages/clock/clock'
                            })
                        }
                    })
                    console.log('进来了您已加入项目', res.params.isAuthed)
                    if (!res.params.isAuthed) {
                        console.log('已加入项目但未核实')
                        this.queryRelations(res.companyId)
                    }
                    return
                }
                if (res.wesureState !== 0) {
                    this.setData({
                        projectName: res.projectName,
                        companyName: res.companyName,
                        serveCompanyName: res.serveCompanyName,
                        btnText: '该项目已过期',
                    })
                    return
                }
                this.setData({
                    projectId: insuranceId,
                    projectName: res.projectName,
                    companyName: res.companyName,
                    companyId: res.companyId,
                    serveCompanyName: res.serveCompanyName,
                    coord,
                })
                joinPayProject({
                    createUserId: userId,
                    userId: user.userId,
                    projectId: insuranceId,
                    joinType: 0,
                }).then(() => {
                    this.setData({
                        projectName: res.projectName,
                        serveCompanyName: res.serveCompanyName,
                        btnText: '返回',
                        callBack: () => {
                            wx.switchTab({
                                url: '/pages/index/index'
                            })
                        }
                        // callBack: app.globalData.gscJoin
                    })
                    toast('去扫脸')
                    this.queryRelations(res.companyId)
                    return
                }).catch((rej) => {
                    console.log(rej, 'rejrej')
                    if (rej.data.code === 500) {
                        this.setData({
                            btnText: '返回',
                            titleText: '加入失败',
                            titleTips: rej.data.msg,
                            callBack: () => {
                                wx.switchTab({
                                    url: '/pages/index/index'
                                })
                            }
                        })
                        return
                    }
                    if (rej.data.data === 'checkAge') {
                        setTimeout(() => {
                            wx.switchTab({
                                url: '/pages/index/index'
                            })
                        }, 1500)
                        return
                    }

                })
                return
                // app.confirm('是否加入项目：' + res.projectName).then(() => {
                // 	joinPayProject({
                // 		createUserId: uid,
                // 		userId: user.userId,
                // 		projectId: projectId,
                // 		joinType: 0
                // 	}).then(() => {
                // 		app.toast('加入项目成功', 'success')
                // 		setTimeout(()=>{
                // 			this.getProjectList()
                // 		},1000)
                // 	})
                // })
            })
        })
    },
    // 获取员工位置
    getPosition() {
        return new Promise((resolve, reject) => {
            wx.getLocation({
                type: 'gcj02',
                isHighAccuracy: true,
                success: res => {
                    this.data.markers.push({
                        iconPath: '/assets/img/join/position.png',
                        longitude: res.longitude,
                        latitude: res.latitude,
                        width: 28,
                        height: 28
                    })
                    // 地理位置
                    this.setData({
                        longitude: res.longitude,
                        latitude: res.latitude,
                        markers: this.data.markers
                    })
                    resolve()
                },
                fail(error) {
                    console.log(error)
                    wx.showModal({
                        title: '温馨提示',
                        content: '小程序将获取您的授权用来显示位置信息,进行打卡操作',
                        success: res => {
                            if (res.confirm) {
                                wx.openSetting({
                                    success(res) {
                                        if (res.authSetting['scope.userLocation']) {
                                            return this.getPosition()
                                        } else {
                                            reject()
                                            app.toast('授权获取失败，无法打开，请确认后再试')
                                        }
                                    },
                                    fail() {
                                        app.toast('授权获取失败，无法打开，请确认后再试')
                                        reject()
                                    }
                                })
                            }
                        },
                        fail() {
                            app.toast('授权获取失败，无法打开，请确认后再试')
                            reject()
                        }
                    })
                }
            })
        })
    },
    // 微工卡核身
    queryRelations(companyId) {
        querySalaryCard(companyId).then((res) => {
            if (!res.isOpenSalaryCard) {
                app.alert('该公司暂未开通微工卡，暂不可投保')
                return
            }
            // .split('&')[0].split('=')[1]
            //  || decodeURIComponent(this.data.options.scene).split('&')[0].split('=')[1]
            verifyFace({
                openid: user.openid,
                companyId: companyId,
                projectId: this.data.projectId,
                employerName: this.data.serveCompanyName,
                projectName: this.data.serveCompanyName,
                userName: user.userName,
                idCardNumber: user.cardNo,
                employmentType: 'SHORT_TERM_EMPLOYMENT',
                authenticateType: 'INSURANCE'
            }).then(res => {
                this.data.companyId = companyId
                this.setData({
                    authenticateNumber: res.authenticateNumber
                })
                console.log(this.data.companyId, 'this.data.companyId')
            })
        }, err => {
            app.alert('您还未开启微工卡授权，授权后才可打卡核身').then(() => {
                if (!err) {
                    app.alert('该公司暂未开通微工卡，暂不可投保')
                    return
                }
                openSalaryCard(companyId)
            })
        })
    }
})